import shp
import pyglet
from pyglet.gl import *

class MainWindow(pyglet.window.Window):
    def __init__(self):
        super(MainWindow, self).__init__(width=512, height=512,resizable=True, visible=False, fullscreen=False)
        self.set_caption("Phillip's GIS")

                # Set up the key handler
        self.keys = pyglet.window.key.KeyStateHandler()
        self.push_handlers(self.keys)

        # Call the update method every 60th of a second.
        pyglet.clock.schedule_interval(self.update, 1/60.0)
        
        # Setup OpenGL settings.
        glDisable(GL_DEPTH_TEST)
        glEnable(GL_CULL_FACE)
        glDisable(GL_DITHER)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glClearColor(1,1,1,1)
        glPointSize(3.0)

        # Create the window controller object and set it as the active controller.
        self.window_controller = WindowController(self)
        self.window_controller.on_resize(self.width, self.height)
        self.push_handlers(self.window_controller)
        self.active_controller = self.window_controller

    def on_draw(self):
        self.active_controller.draw()
        
    def update(self, dt):
        self.active_controller.update(dt)


class GISMap(object):
    def __init__(self, window):
        self.window = window
        self.facilities = shp.Shapefile('sourcedata/facilities/facilities.shp')
        self.x0 = self.facilities.xmin
        self.y0 = self.facilities.ymin        
        self.width = self.facilities.xmax - self.facilities.xmin
        self.height = self.facilities.ymax - self.facilities.ymin

        #self.streets = shp.Shapefile('sourcedata/STREETS/STREETS.shp')
        self.parks = shp.Shapefile('sourcedata/coa_parks/city_of_austin_parks.shp')
        
    def draw(self,debug=False):
        """Draws the map background and all the objects in the map."""

        glClear(GL_COLOR_BUFFER_BIT)

        glLoadIdentity()
        glTranslatef(-self.x0, -self.y0, 0)

        # glColor3f(0,0,0)
        # for line in self.streets.polylines:
        #     glBegin(GL_LINE_STRIP)
        #     for point in line.vertices:
        #         glVertex2f(*point)
        #     glEnd()

        #glColor3f(0,1,0)
        #for polygon in self.parks.polygons:
        #    glBegin(GL_POLYGON)
        #    for point in polygon.vertices:
        #        glVertex2f(*point)
        #    glEnd()
            
        glColor3f(1,0,0)
        glBegin(GL_POINTS)
        glVertex2f(0,0)
        for point in self.facilities.points:
            glVertex2f(point.x, point.y)
        glEnd()


        if debug:
            pass

    def update(self, dt):
        pass

class WindowController(object):
    def __init__(self, window):
        self.window = window
        self.map = GISMap(window)

        self.fps_display = pyglet.clock.ClockDisplay(color=(1,1,1,1))
        self.debug_draw = False
        self.debug_fps = False

        glClear(GL_COLOR_BUFFER_BIT)

    def on_resize(self, width, height):
        aspect_ratio = float(width) / float(height)
        self.view_width = self.map.width
        self.view_height = self.map.height
        glViewport(0, 0, width, height)
        self.set_projection()

    def set_projection(self):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, self.view_width, 0, self.view_height, -1, 1)
        #print self.view_width, self.view_height
        glMatrixMode(GL_MODELVIEW)

    def update(self, dt):
        self.map.update(dt)

    def draw(self):
        self.set_projection()
        glLoadIdentity()
        self.map.draw(self.debug_draw)
        if self.debug_fps:
            glLoadIdentity()
            self.fps_display.draw()

    #def on_mouse_press(self, x, y, button, modifiers):
    #    view_x = float(x) * self.view_width / float(self.window.width)
    #    view_y = float(y) * self.view_height / float(self.window.height)
        # do nothing
        
    def on_key_press(self, symbol, modifiers):
        if symbol == pyglet.window.key.ESCAPE:
            pyglet.app.exit()
        elif symbol == pyglet.window.key._0 or symbol == pyglet.window.key.F:
            self.window.set_fullscreen(not self.window.fullscreen)
        elif symbol == pyglet.window.key._1:
            self.debug_fps = not self.debug_fps
        elif symbol == pyglet.window.key._2:
            self.debug_draw = not self.debug_draw
        elif symbol == pyglet.window.key.S:
            pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot.png')

    def on_mouse_press(self, x, y, button, modifiers):
        self.start_point = (x,y)
        
    def on_mouse_release(self, x, y, button, modifiers):
        if not self.start_point: return
        self.end_point = (x, y)
        dx = self.end_point[0] - self.start_point[0]
        dy = self.end_point[1] - self.start_point[1]
        self.translate_map(-dx, -dy)
        self.start_point = None
        
    def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
        self.start_point = (x,y)
        self.translate_map(-dx, -dy)        

    def translate_map(self, dx, dy):
        maxdim = max(self.map.width, self.map.height)
        dx *= float(maxdim)/self.window.width
        dy *= float(maxdim)/self.window.height
        self.map.x0 += dx
        self.map.y0 += dy


def run_application():
    window = MainWindow()
    window.clear()
    window.flip()
    window.set_visible(True)
    pyglet.app.run()

if __name__ == '__main__':
    run_application()
